/*
 * @Author: your name
 * @Date: 2020-08-23 18:37:36
 * @LastEditTime: 2020-08-28 08:46:25
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \新建文件夹\two-app\src\router\index.js
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import cookie from 'js-cookie'
import store from '../store'
Vue.use(VueRouter)

// const originalPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location, onResolve, onReject) {
//   if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
//   return originalPush.call(this, location).catch(err => err)
// }

// const originalReplace = VueRouter.prototype.replace
// VueRouter.prototype.replace = function repalce(location, onResolve, onReject) {
//   if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
//   return originalReplace.call(this, location).catch(err => err)
// }
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: 'Login' */ '../views/Login.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(async (to, form, next) => {
  const userInfo = sessionStorage.getItem('userInfo')
  const userId = sessionStorage.getItem('user_id')
  // 判断是否登陆
  if (userId) {
    // 判断是否刷新
    if (store.state.GetAuth.filterRoute.length === 0) {
      await store.dispatch('GetAuth/getRoutes', userInfo)
      // console.log(to.fullPath)
      next(to.fullPath)
    } else {
      next()
    }
    if (to.path === '/login') {
      cookie.remove('token')
      next()
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
